#include "widget_doctor.h"
#include "ui_widget_doctor.h"

Widget_doctor::Widget_doctor(QWidget *parent, QString userId, DoctorManagement *dm, PatientManagement *pm, AppointmentManagement *am, AdviceManagement *adm, PrescriptionManagement *pscm, MedicalRecordManagement *mrm)
    : QWidget(parent), ui(new Ui::Widget_doctor),
        user_id(userId), d_m(dm), p_m(pm), a_m(am),
        ad_m(adm), psc_m(pscm), mr_m(mrm)
{
    ui->setupUi(this);

    initUserInfo();

    MainWidget* mainWidget = qobject_cast<MainWidget*>(parent);
    if (mainWidget) {
        // 连接信号和槽
        connect(this, &Widget_doctor::requestChatClient, mainWidget, &MainWidget::handleDoctorChatRequest);
    }
}

void Widget_doctor::initUserInfo()
{
    QVariantMap userInfo = d_m->GetInfo(user_id); // 调用 GetInfo

    if (!userInfo.isEmpty()) {
        // 提取信息
        QString username = userInfo.value("username").toString();
        QString profession = userInfo.value("profession").toString();
        int age = userInfo.value("age").toInt();
        QString gender = userInfo.value("gender").toString();
        QString phone = userInfo.value("phone").toString();
        QString address = userInfo.value("address").toString();

        // LOG_DEBUG() << "frofession: " << profession;

        // 设置到界面组件
        ui->name_ld->setText(username);
        ui->profession_ld->setText(profession);
        ui->age_ld->setText(QString::number(age));
        ui->gender_ld->setText(gender);
        ui->phone_ld->setText(phone);
        ui->address_ld->setText(address);
    } else {
        // 处理没有用户信息的情况
        ui->name_ld->setText("未找到用户信息");
        ui->age_ld->clear();
        ui->gender_ld->clear();
        ui->phone_ld->clear();
        ui->address_ld->clear();
    }
}


Widget_doctor::~Widget_doctor()
{
    delete ui;
}

void Widget_doctor::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
//    QPixmap pixmap=QPixmap(":/bakground/image/patient_background.png");
//    pixmap = pixmap.scaled(this->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
//    painter.drawPixmap(0,0,pixmap);
}

void Widget_doctor::incomingConnection(qintptr socketDescriptor) {
    QTcpSocket *socket = new QTcpSocket(this);
    socket->setSocketDescriptor(socketDescriptor);

    connect(socket, &QTcpSocket::readyRead, [socket]() {
        // 处理接收到的消息
        QByteArray data = socket->readAll();
        qDebug() << "Received from doctor: " << data;
    });

    connect(socket, &QTcpSocket::disconnected, socket, &QTcpSocket::deleteLater);
}

void Widget_doctor::on_pushButton_back_clicked()
{
    emit this->back();
}

void Widget_doctor::on_edit_btn_clicked()
{
    ui->show->setCurrentIndex(0);
}

void Widget_doctor::on_appointment_btn_clicked()
{
    ui->show->setCurrentIndex(1); // 切换到显示患者信息的页面

    // LOG_DEBUG() << "userid: " << user_id;
    // 获取患者 ID 列表
    QVariantList patient_ids = a_m->GetPaitentInfoByDID(user_id);

    // 清空现有数据并重置行数
    ui->patient_tab_widget->setRowCount(0); // 只重置行数

    // 设置表头（如果还未设置）
    if (ui->patient_tab_widget->horizontalHeader()->count() == 0) {
        ui->patient_tab_widget->setColumnCount(6); // 设置列数
        QStringList headers = { "患者ID", "姓名", "年龄", "性别", "电话", "地址" }; // 根据需要调整列标题
        ui->patient_tab_widget->setHorizontalHeaderLabels(headers);
    }

    // 遍历 patient_ids 并添加到 patient_tab_widget
    for (const QVariant &p_id_variant : patient_ids) {
        QString p_id = p_id_variant.toString(); // 将 QVariant 转换为 QString
        QVariantMap patient_info = p_m->GetInfo(p_id); // 获取患者信息

        int row = ui->patient_tab_widget->rowCount();
        ui->patient_tab_widget->insertRow(row); // 插入新行

        // 将患者信息填充到对应的单元格中
        ui->patient_tab_widget->setItem(row, 0, new QTableWidgetItem(p_id)); // 假设显示患者ID
        ui->patient_tab_widget->setItem(row, 1, new QTableWidgetItem(patient_info.value("username").toString()));
        ui->patient_tab_widget->setItem(row, 2, new QTableWidgetItem(patient_info.value("age").toString()));
        ui->patient_tab_widget->setItem(row, 3, new QTableWidgetItem(patient_info.value("gender").toString()));
        ui->patient_tab_widget->setItem(row, 4, new QTableWidgetItem(patient_info.value("phone").toString()));
        ui->patient_tab_widget->setItem(row, 5, new QTableWidgetItem(patient_info.value("address").toString()));
    }
}


void Widget_doctor::on_diag_btn_clicked()
{
    ui->show->setCurrentIndex(2);
}

void Widget_doctor::on_graph_btn_clicked()
{
    ui->show->setCurrentIndex(5);

    // 创建 UI 元素
    graph_type_combo_box = new QComboBox();
    graph_type_combo_box->addItem("树状图");
    graph_type_combo_box->addItem("折线图");
    graph_type_combo_box->addItem("扇形图");

    generate_graph_btn = new QPushButton("生成图表");

    input_data_line_edit = new QLineEdit();
    input_data_line_edit->setPlaceholderText("请输入数据，逗号分隔（例如：10, 20, 30, 40）");

    chartView = new QChartView();

//    if (layout()) {
//        delete layout();  // 删除现有布局
//    }

    // 创建新布局
    ui->formLayout_5->addWidget(new QLabel("选择图表类型："));
    ui->formLayout_5->addWidget(graph_type_combo_box);
    ui->formLayout_5->addWidget(new QLabel("输入数据："));
    ui->formLayout_5->addWidget(input_data_line_edit);
    ui->formLayout_5->addWidget(generate_graph_btn);
    ui->formLayout_5->addWidget(chartView);

    // 连接信号与槽
    connect(generate_graph_btn, &QPushButton::clicked, this, &Widget_doctor::on_generate_graph_btn_clicked);
}


void Widget_doctor::on_submit_instruction_btn_clicked()
{
    QString pId = ui->patientID_ld->text();
    QString instruction = ui->instruction_td->toPlainText();

    // 可以增添：判断病人是否是预约病人、是否已经写过医嘱
    // TODO...

    bool ret = ad_m->Insert(user_id, pId, instruction);
    if(!ret) {
        LOG_ERROR() << "insert error when submit instruction";
        Config::popMessageBox("ERROR", "提交医嘱失败", "error");
        return;
    }
    Config::popMessageBox("ERROR", "医嘱提交成功", "ok");
}

void Widget_doctor::on_medical_record_btn_clicked()
{
    ui->show->setCurrentIndex(3);
}

void Widget_doctor::on_submit_medical_record_btn_clicked()
{
    QString patientId = ui->patientID_ld_2->text();
    QString disease_name = ui->disease_ld->text();
    QString details = ui->medical_record_td->toPlainText();

    // 可以增添：判断病人是否是预约病人、是否已经写过病历
    // TODO..

    bool ret = mr_m->Insert(patientId, user_id, disease_name, details);

    if(!ret) {
        LOG_ERROR() << "insert error when submit instruction";
        Config::popMessageBox("ERROR", "提交病历失败", "error");
        return;
    }
    Config::popMessageBox("ERROR", "病历提交成功", "ok");
}

void Widget_doctor::on_submit_prescription_btn_clicked()
{
    QString patient_id = ui->patientID_ld_3->text();
    QString drug_name = ui->drug_ld->text();
    QString dose = ui->dose_ld->text();
    QString frequency = ui->frequency_ld->text();
    QString cost = ui->cose_ld->text();

    // 获取与患者相关的建议ID
    QVariantList advice_ids = ad_m->GetAdviceIdByID(patient_id, user_id);

    // 确保有建议ID
    if (advice_ids.isEmpty()) {
        LOG_ERROR() << "No advice ID found for patient:" << patient_id;
        Config::popMessageBox("ERROR", "未找到相关建议ID", "error");
        return;
    }

    // 暂时只考虑只有一个对应ID
    QString advice_id = advice_ids[0].toString(); // 将 QVariant 转换为 QString

    // 插入处方
    bool ret = psc_m->Insert(advice_id, drug_name, dose, frequency, cost);
    if (!ret) {
        LOG_ERROR() << "Insert error when submitting prescription for patient:" << patient_id;
        Config::popMessageBox("ERROR", "提交处方失败", "error");
        return;
    }

    // 提交成功
    Config::popMessageBox("SUCCESS", "处方提交成功", "ok");
}


void Widget_doctor::on_prescription_btn_clicked()
{
    ui->show->setCurrentIndex(4);
}

void Widget_doctor::on_exit_btn_clicked()
{
    this->close();
}

void Widget_doctor::on_update_btn_clicked()
{
    // 从界面上获取用户输入的值
    QString name = ui->name_ld->text();
    QString profession = ui->profession_ld->text();
    int age = ui->age_ld->text().toInt();
    QString gender = ui->gender_ld->text();
    QString phone = ui->phone_ld->text();
    QString address = ui->address_ld->text();

    // 构建 JSON 对象，用于更新
    QJsonObject json_object;
    json_object["id"] = user_id;  // 假设 user_id 已经在类的成员中定义
    json_object["username"] = name;
    json_object["age"] = age;
    json_object["gender"] = gender;
    json_object["phone"] = phone;
    json_object["address"] = address;
    json_object["profession"] = profession;

    // 调用更新方法
    bool ret = d_m->Update(json_object);  // 假设 d_m 是医生管理对象的实例

    // 根据更新结果弹出消息框
    if (!ret) {
        LOG_ERROR() << "Update doctor information failed";  // 错误日志
        Config::popMessageBox("OK", "修改信息失败", "error");  // 弹出失败消息框
    } else {
        LOG_INFO() << "Doctor information updated successfully";  // 成功日志
        Config::popMessageBox("OK", "修改信息成功", "ok");  // 弹出成功消息框
    }
}


void Widget_doctor::showChatClient() {
    ChatWidget *chatWidget = new ChatWidget("doctor", this);
    chatWidget->show();
}

void Widget_doctor::on_chat_btn_clicked()
{
    emit requestChatClient();
}

void Widget_doctor::on_generate_graph_btn_clicked()
{
    QString input_data = input_data_line_edit->text();
    if (input_data.isEmpty()) {
        // 如果用户没有输入数据，显示一个错误提示
        return;
    }

    // 将输入的数据按逗号分割并转换为整数列表
    QStringList dataList = input_data.split(',');
    QVector<int> data;
    for (const QString &str : dataList) {
        bool ok;
        int value = str.trimmed().toInt(&ok);
        if (ok) {
            data.append(value);
        } else {
            // 数据转换失败，显示错误信息并返回
            return;
        }
    }

    // 获取选择的图表类型
    QString chartType = graph_type_combo_box->currentText();

    if (chartType == "树状图") {
        // 创建树状图
        QBarSeries *barSeries = new QBarSeries();
        QBarSet *barSet = new QBarSet("数据");

        // 将数据添加到树状图
        for (int value : data) {
            *barSet << value;
        }
        barSeries->append(barSet);

        QChart *chart = new QChart();
        chart->addSeries(barSeries);
        chart->setTitle("树状图");

        // 设置Y轴的范围，使图表不那么细
        QValueAxis *axisY = new QValueAxis();
        axisY->setRange(0, *std::max_element(data.begin(), data.end()) + 10);  // Y轴最大值稍微大一点
        chart->setAxisY(axisY, barSeries);  // 设置Y轴

        // 默认设置X轴
        chart->createDefaultAxes();

        chartView->setChart(chart);
        chartView->setRenderHint(QPainter::Antialiasing);
    }
    else if (chartType == "折线图") {
        // 创建折线图
        QLineSeries *lineSeries = new QLineSeries();
        for (int i = 0; i < data.size(); ++i) {
            lineSeries->append(i, data[i]);
        }

        QChart *chart = new QChart();
        chart->addSeries(lineSeries);
        chart->setTitle("折线图");

        // 设置Y轴的范围，使图表不那么细
        QValueAxis *axisY = new QValueAxis();
        axisY->setRange(0, *std::max_element(data.begin(), data.end()) + 10);  // Y轴最大值稍微大一点
        chart->setAxisY(axisY, lineSeries);

        // 设置X轴的范围
        QValueAxis *axisX = new QValueAxis();
        axisX->setRange(0, data.size() - 1);  // X轴从 0 到数据的长度
        chart->setAxisX(axisX, lineSeries);

        chartView->setChart(chart);
        chartView->setRenderHint(QPainter::Antialiasing);
    }
    else if (chartType == "扇形图") {
        // 创建扇形图
        QPieSeries *pieSeries = new QPieSeries();
        for (int i = 0; i < data.size(); ++i) {
            pieSeries->append(QString("数据 %1").arg(i + 1), data[i]);
        }

        QChart *chart = new QChart();
        chart->addSeries(pieSeries);
        chart->setTitle("扇形图");

        chartView->setChart(chart);
        chartView->setRenderHint(QPainter::Antialiasing);
    }

    // 确保图表显示区域足够大，避免图表显示太小
    chartView->resize(800, 600);  // 调整图表显示区域
}
